package mobi.weq.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import mobi.weq.db.Database;
import mobi.weq.model.HealthCondition;
import mobi.weq.model.User;

public class HealthConditionDao {
	public synchronized int addHealthCondition(HealthCondition hc)
			throws SQLException {
		Connection c = Database.getConnection();
		String query = "insert into health_condition(user_id,respiratory_infections,asthma,lung_disease,heart_disease,allergies) values(?,?,?,?,?,?)";
		PreparedStatement ps = c.prepareStatement(query);
		ps.setString(1, hc.getUserId());
		ps.setInt(2, hc.isRespiratory_infections() ? 1 : 0);
		ps.setInt(3, hc.isAsthma() ? 1 : 0);
		ps.setInt(4, hc.isHeart_disease() ? 1 : 0);
		ps.setInt(5, hc.isLung_disease() ? 1 : 0);
		ps.setInt(6, hc.isAllergies() ? 1 : 0);
		return ps.executeUpdate();

	}

	public HealthCondition getUserHealthCondition(User u) throws SQLException {

		Connection c = Database.getConnection();
		String query = "select * from health_condition where user_id=?";
		PreparedStatement ps = c.prepareStatement(query);
		ps.setString(1, u.getUserId());

		ResultSet rs = ps.executeQuery();

		HealthCondition hc = null;
		if (rs.next()) {
			hc = new HealthCondition();
			hc.setUserId(rs.getString(1));
			hc.setAllergies(rs.getInt(2) == 1);
			hc.setAsthma(rs.getInt(3) == 1);
			hc.setHeart_disease(rs.getInt(4) == 1);
			hc.setLung_disease(rs.getInt(5) == 1);
			hc.setRespiratory_infections(rs.getInt(6) == 1);
		}
		return hc;
	}

	public int updateHealthCondition(HealthCondition hc) throws SQLException {

		Connection c = Database.getConnection();
		String query = "update health_condition set respiratory_infections=?,asthma=?,lung_disease=?,heart_disease=?,allergies=? where user_id=?";
		PreparedStatement ps = c.prepareStatement(query);
		ps.setInt(1, hc.isRespiratory_infections() ? 1 : 0);
		ps.setInt(2, hc.isAsthma() ? 1 : 0);
		ps.setInt(3, hc.isHeart_disease() ? 1 : 0);
		ps.setInt(4, hc.isLung_disease() ? 1 : 0);
		ps.setInt(5, hc.isAllergies() ? 1 : 0);
		ps.setString(6, hc.getUserId());
		return ps.executeUpdate();
	}

}
